<template>
  <div class="flaw-statistic-container">
    <!-- 时间选择区域 -->
    <el-card shadow="never" class="time-selector-card">
      <div class="time-selector">
        <div class="time-inputs">
          <div class="time-item">
            <label>起始时间：</label>
            <el-date-picker
              v-model="startTime"
              type="datetime"
              placeholder="选择起始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
          <div class="time-item">
            <label>结束时间：</label>
            <el-date-picker
              v-model="endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
        </div>
        <el-button type="primary" @click="handleQuery" :loading="loading">
          查询
        </el-button>
      </div>
    </el-card>

    <!-- 统计数据区域 -->
    <el-card shadow="never" class="statistics-card">
      <div class="statistics-container">
        <!-- 任务统计 -->
        <div class="task-statistics">
          <div class="stat-title">任务统计</div>
          <div class="stat-item">
            <div class="stat-label">任务总数</div>
            <div class="stat-value">{{ taskStats.totalTasks }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">任务总距离</div>
            <div class="stat-value">{{ taskStats.totalDistance }}km</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">任务参与人数</div>
            <div class="stat-value">{{ taskStats.totalParticipants }}</div>
          </div>
        </div>

        <!-- 饼状图区域 -->
        <div class="chart-container">
          <div ref="pieChart" class="pie-chart"></div>
          <div class="chart-legend">
            <div v-for="item in flawTypeData" :key="item.name" class="legend-item">
              <span class="legend-color" :style="{ backgroundColor: item.color }"></span>
              <span class="legend-text">{{ item.name }}</span>
            </div>
          </div>
        </div>

        <!-- 缺陷统计 -->
        <div class="flaw-statistics">
          <div class="stat-title">缺陷统计</div>
          <div class="stat-item">
            <div class="stat-label">缺陷总数</div>
            <div class="stat-value">{{ flawStats.totalFlaws }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">已解决缺陷数</div>
            <div class="stat-value">{{ flawStats.resolvedFlaws }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">未解决缺陷数</div>
            <div class="stat-value">{{ flawStats.unresolvedFlaws }}</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 路线可视化区域 -->
    <el-card shadow="never" class="route-visualization-card">
      <div class="route-container">
        <div class="route-title">全路线缺陷分布统计</div>
        <div class="route-line-container">
          <div class="route-line">
            <div 
              v-for="(segment, index) in routeSegments" 
              :key="index"
              class="route-segment"
              :class="getSegmentClass(segment.flawCount)"
              :style="{ backgroundColor: getSegmentColor(segment.flawCount) }"
              @click="handleSegmentClick(segment)"
              @mouseenter="handleSegmentHover(segment, true)"
              @mouseleave="handleSegmentHover(segment, false)"
              :title="`${segment.start}m - ${segment.end}m: ${segment.flawCount}个缺陷`"
            ></div>
          </div>
          <div class="route-labels">
            <span class="label-start">0米</span>
            <span class="label-end">3688米</span>
          </div>
        </div>
        <div class="route-legend">
          <div class="legend-item" v-for="range in flawCountRanges" :key="range.label">
            <span class="legend-color" :style="{ backgroundColor: range.color }"></span>
            <span class="legend-text">{{ range.label }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 缺陷类型详情模态框 -->
    <FlawTypeDetail
      v-model:visible="typeDetailVisible"
      :flaw-type="selectedFlawType"
      :start-time="startTime"
      :end-time="endTime"
    />

    <!-- 路段缺陷详情模态框 -->
    <FlawCountDetail
      v-model:visible="countDetailVisible"
      :segment="selectedSegment"
      :start-time="startTime"
      :end-time="endTime"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElCard, ElDatePicker, ElButton, ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { getTasksByTime } from '@/api/tasks';
import { getFlawsByTime } from '@/api/flaws';
import FlawTypeDetail from '@/components/flaw/FlawTypeDetail.vue';
import FlawCountDetail from '@/components/flaw/FlawCountDetail.vue';

// 响应式数据
const loading = ref(false);
const startTime = ref('');
const endTime = ref('');
const pieChart = ref(null);
let chartInstance = null;

// 统计数据
const taskStats = reactive({
  totalTasks: 0,
  totalDistance: 0,
  totalParticipants: 0
});

const flawStats = reactive({
  totalFlaws: 0,
  resolvedFlaws: 0,
  unresolvedFlaws: 0
});

// 饼状图数据
const flawTypeData = ref([
  { name: '裂缝', value: 45, color: '#FF6B6B' },     // 红色
  { name: '渗水', value: 38, color: '#4D96FF' },     // 蓝色
  { name: '钢筋锈蚀', value: 32, color: '#FFB562' }, // 橙色
  { name: '混凝土剥落', value: 28, color: '#9575DE' }, // 紫色
  { name: '脱空', value: 25, color: '#96CEB4' },     // 薄荷绿
  { name: '错台', value: 22, color: '#FFD93D' },     // 金黄色
  { name: '接缝破损', value: 18, color: '#6C5B7B' }, // 深紫色
  { name: '防水板破损', value: 15, color: '#45B7D1' }, // 天蓝色
  { name: '螺栓松动', value: 12, color: '#F8A978' }, // 橘粉色
  { name: '其他', value: 8, color: '#87A2FB' }      // 淡蓝色
]);

// 缺陷数量颜色范围 - 从绿色渐变到红色
const flawCountRanges = [
  { label: '0个', color: '#E8E8E8', min: 0, max: 0 },         // 灰色
  { label: '1-2个', color: '#C8E6C9', min: 1, max: 2 },       // 浅绿色
  { label: '3-4个', color: '#81C784', min: 3, max: 4 },       // 绿色
  { label: '5-6个', color: '#FFF59D', min: 5, max: 6 },       // 浅黄色
  { label: '7-8个', color: '#FFE082', min: 7, max: 8 },       // 黄色
  { label: '9-10个', color: '#FFCC80', min: 9, max: 10 },     // 浅橙色
  { label: '11-12个', color: '#FFB74D', min: 11, max: 12 },   // 橙色
  { label: '13-14个', color: '#FF8A65', min: 13, max: 14 },   // 深橙色
  { label: '15-16个', color: '#FF5252', min: 15, max: 16 },   // 红色
  { label: '17个以上', color: '#D32F2F', min: 17, max: Infinity } // 深红色
];

// 路线分段数据
const routeSegments = ref([]);

// 模态框控制
const typeDetailVisible = ref(false);
const countDetailVisible = ref(false);
const selectedFlawType = ref('');
const selectedSegment = ref(null);

// 根据缺陷数据生成路线分段
const generateRouteSegments = (flaws) => {
  const segments = [];
  const totalDistance = 3688;
  const segmentLength = 250;
  
  for (let i = 0; i <= totalDistance; i += segmentLength) {
    const start = i;
    const end = Math.min(i + segmentLength, totalDistance);
    
    // 统计该路段内的缺陷数量
    const flawCount = flaws.filter(flaw => {
      const location = parseFloat(flaw.flawDistance) || 0;
      return location >= start && location < end;
    }).length;
    
    segments.push({
      start,
      end,
      flawCount,
      id: segments.length
    });
  }
  
  routeSegments.value = segments;
};

// 生成随机颜色
const generateRandomColor = () => {
  // 使用HSL颜色空间生成更协调的随机颜色
  const hue = Math.floor(Math.random() * 360); // 0-359度
  const saturation = Math.floor(Math.random() * 30) + 50; // 50-80%饱和度
  const lightness = Math.floor(Math.random() * 20) + 45; // 45-65%亮度
  return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
};

// 生成一些有意义的示例数据
const generateSampleData = () => {
  const flaws = [];
  return flaws;
};

// 初始化路线分段（用于初始加载时的默认数据）
const initRouteSegments = () => {
  const sampleFlaws = generateSampleData();
  generateRouteSegments(sampleFlaws);
};

// 获取分段颜色
const getSegmentColor = (flawCount) => {
  const range = flawCountRanges.find(r => flawCount >= r.min && flawCount <= r.max);
  return range ? range.color : '#e8f5e8';
};

// 获取分段样式类
const getSegmentClass = (flawCount) => {
  return `flaw-count-${Math.min(Math.floor(flawCount / 5), 5)}`;
};

// 初始化饼状图
const initPieChart = () => {
  if (!pieChart.value) return;
  
  chartInstance = echarts.init(pieChart.value);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '缺陷类型',
        type: 'pie',
        radius: ['28%', '65%'],
        center: ['50%', '42%'],
        data: flawTypeData.value.map(item => ({
          value: item.value,
          name: item.name,
          itemStyle: { color: item.color }
        })),
        emphasis: {
          scale: true,
          scaleSize: 10
        },
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{d}%',
          fontSize: 13,
          fontWeight: 'normal',
          color: '#333',
          distanceToLabelLine: 8
        },
        labelLine: {
          show: true,
          length: 20,
          length2: 15,
          lineStyle: {
            color: '#999',
            width: 1
          }
        }
      }
    ]
  };
  
  chartInstance.setOption(option);
  
  // 点击事件
  chartInstance.on('click', (params) => {
    selectedFlawType.value = params.name;
    typeDetailVisible.value = true;
  });
};

// 查询数据
const handleQuery = async () => {
  loading.value = true;
  try {
    // 如果没有选择时间范围，使用默认时间
    const queryStartTime = startTime.value || '';
    const queryEndTime = endTime.value || '';
    
    // 并行请求任务数据和缺陷数据
    const [taskResponse, flawResponse] = await Promise.all([
      getTasksByTime(queryStartTime, queryEndTime),
      getFlawsByTime(queryStartTime, queryEndTime)
    ]);

    // 处理任务统计数据
    if ((taskResponse.data.code === '200' || taskResponse.data.code === 200) && taskResponse.data.rows) {

      const tasks = taskResponse.data.rows
      taskStats.totalTasks = taskResponse.data.total
      
      // 计算总距离和参与人数（隧道总长按3688米计算）
      const completedTasks = tasks.filter(task => task.taskStatus === '已完成');
      const totalDistance = completedTasks.length * 3.688; // 每个任务完成一次全程巡检
      const participants = new Set(tasks.map(task => task.executor).filter(Boolean));
      
      taskStats.totalDistance = Math.round(totalDistance * 100) / 100; // 保留两位小数
      taskStats.totalParticipants = participants.size;
    }
    
    // 处理缺陷统计数据
    if ((flawResponse.data.code === '200' || flawResponse.data.code === 200) && flawResponse.data.rows) {
      const flaws = flawResponse.data.rows
      flawStats.totalFlaws = flawResponse.data.total
      
      // 计算已解决和未解决缺陷数（根据confirmed和uploaded字段）
      const resolvedCount = flaws.filter(flaw => flaw.confirmed && flaw.uploaded).length;
      flawStats.resolvedFlaws = resolvedCount;
      flawStats.unresolvedFlaws = flawStats.totalFlaws - resolvedCount;
      
      // 统计缺陷类型数据
      const typeStats = {};
      flaws.forEach(flaw => {
        const type = flaw.flawType || '其他';
        typeStats[type] = (typeStats[type] || 0) + 1;
      });
      
      // 更新饼图数据 - 使用预定义的颜色配置
      const typeColors = {
        '裂缝': '#FF6B6B',     // 红色
        '渗水': '#4D96FF',     // 蓝色
        '钢筋锈蚀': '#FFB562', // 橙色
        '混凝土剥落': '#9575DE', // 紫色
        '脱空': '#96CEB4',     // 薄荷绿
        '错台': '#FFD93D',     // 金黄色
        '接缝破损': '#6C5B7B', // 深紫色
        '防水板破损': '#45B7D1', // 天蓝色
        '螺栓松动': '#F8A978', // 橘粉色
        '其他': '#87A2FB'      // 淡蓝色
      };
      
      const newFlawTypeData = Object.entries(typeStats).map(([name, value]) => ({
        name,
        value,
        color: typeColors[name] || generateRandomColor() // 如果没有预定义颜色，使用随机颜色
      }));
      
      flawTypeData.value = newFlawTypeData;
      
      // 更新图表
      if (chartInstance) {
        chartInstance.setOption({
          series: [{
            data: newFlawTypeData.map(item => ({
              value: item.value,
              name: item.name,
              itemStyle: { color: item.color }
            })),
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{d}%',
              fontSize: 13,
              fontWeight: 'normal',
              color: '#333',
              distanceToLabelLine: 8
            },
            labelLine: {
              show: true,
              length: 20,
              length2: 15,
              lineStyle: {
                color: '#999',
                width: 1
              }
            }
          }]
        });
      }
      
      // 生成路线分段数据
      generateRouteSegments(flaws);
    }
    
    ElMessage.success('查询完成');
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error(error.message || '查询失败');
  } finally {
    loading.value = false;
  }
};

// 路段点击事件
const handleSegmentClick = (segment) => {
  selectedSegment.value = segment;
  countDetailVisible.value = true;
};


// 初始化
onMounted(async () => {
  initRouteSegments();
  
  await nextTick();
  initPieChart();
  
  // 初始加载数据（不指定时间范围，获取全部数据）
  await handleQuery();
});
</script>

<style lang="scss" scoped>
@use '../assets/scss/variables' as *;

.flaw-statistic-container {
  padding: $page-padding;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: $page-padding;
}

.time-selector-card {
  flex: 0 0 auto;
  height: 10%;
}

.time-selector {
  display: flex;
  align-items: center;
  gap: 20px;
  
  .time-inputs {
    display: flex;
    gap: 20px;
    
    .time-item {
      display: flex;
      align-items: center;
      gap: 10px;
      
      label {
        white-space: nowrap;
        color: $text-color-regular;
      }
    }
  }
}

.statistics-card {
  flex: 0 0 auto;
  height: 60%;
}

.statistics-container {
  display: flex;
  height: 100%;
  gap: 20px;
}

.task-statistics,
.flaw-statistics {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  
  .stat-title {
    font-size: 18px;
    font-weight: 600;
    color: $text-color-primary;
    border-bottom: 2px solid $primary-color;
    padding-bottom: 8px;
  }
  
  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .stat-label {
      color: $text-color-regular;
      font-size: 14px;
    }
    
    .stat-value {
      color: $primary-color;
      font-size: 24px;
      font-weight: 600;
    }
  }
}

.chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  overflow: visible;
  
  .pie-chart {
    width: 500px;
    height: 380px;
    cursor: pointer;
    flex-shrink: 0;
  }
  
  .chart-legend {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 15px;
    margin-top: -35px;
    max-width: 500px;
    flex-shrink: 0;
    
    .legend-item {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .legend-color {
        width: 12px;
        height: 12px;
        border-radius: 2px;
        flex-shrink: 0;
      }
      
      .legend-text {
        font-size: 12px;
        color: $text-color-regular;
        white-space: nowrap;
      }
    }
  }
}

.route-visualization-card {
  flex: 0 0 auto;
  height: 30%;
}

.route-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .route-title {
    font-size: 18px;
    font-weight: 600;
    color: $text-color-primary;
    margin-bottom: 20px;
    text-align: center;
  }
}

.route-line-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 50px;
  
  .route-line {
    display: flex;
    height: 40px;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .route-segment {
      flex: 1;
      cursor: pointer;
      transition: all 0.3s ease;
      border-right: 1px solid #fff;
      
      &:hover {
        transform: scaleY(1.2);
        z-index: 10;
        position: relative;
      }
      
      &:last-child {
        border-right: none;
      }
    }
  }
  
  .route-labels {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    padding: 0 10px;
    
    .label-start,
    .label-end {
      font-size: 12px;
      color: $text-color-regular;
    }
  }
}

.route-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 15px;
  
  .legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
    
    .legend-color {
      width: 12px;
      height: 12px;
      border-radius: 2px;
    }
    
    .legend-text {
      font-size: 12px;
      color: $text-color-regular;
    }
  }
}
</style> 